﻿namespace Snipps.Infrastructure.AttachedProperties
{
    using System.Linq;
    using System.Windows;
    using System.Windows.Controls;

    public static class SetLastCaretIndexBehavior
    {
        public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached(
            "IsEnabled", typeof(bool), typeof(SetLastCaretIndexBehavior), new UIPropertyMetadata(false, OnIsEnabledChanged));

        private static void OnIsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var textBox = d as TextBox;
            if (textBox == null)
            {
                return;
            }

            if (e.NewValue is bool == false)
            {
                return;
            }

            if ((bool)e.NewValue)
            {
                textBox.GotFocus += textBox_GotFocus;
                textBox.TextChanged += textBox_TextChanged;
            }
            else
            {
                textBox.GotFocus -= textBox_GotFocus;
                textBox.TextChanged -= textBox_TextChanged;
            }
        }

        private static void textBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!ReferenceEquals(sender, e.OriginalSource))
            {
                return;
            }

            var textBox = e.OriginalSource as TextBox;
            if (textBox != null)
            {
                if (e.Changes.Any())
                {
                    var change = e.Changes.First();
                    if (change.Offset == 0 && change.AddedLength > 0 && change.AddedLength == textBox.Text.Length)
                    {
                        textBox.CaretIndex = textBox.Text.Length;
                    }
                }
            }
        }

        private static void textBox_GotFocus(object sender, RoutedEventArgs e)
        {
            if (!ReferenceEquals(sender, e.OriginalSource))
            {
                return;
            }

            var textBox = e.OriginalSource as TextBox;
            if (textBox != null)
            {
                textBox.CaretIndex = textBox.Text.Length;
            }
        }

        public static void SetIsEnabled(TextBox textBox, bool value)
        {
            textBox.SetValue(IsEnabledProperty, value);
        }

        public static bool GetIsEnabled(TextBox textBox)
        {
            return (bool)textBox.GetValue(IsEnabledProperty);
        }
    }
}